package service

import (
	"fly/global"
	"fly/models"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"github.com/duke-git/lancet/v2/condition"
	"net/url"
)

type SysDictService struct {
	BaseService
}

const (
	DictionaryCacheSimple = "DictionaryCacheSimple:%d"
	DictionaryCacheValue  = "DictionaryCacheValue:%d"
)

// GetPaginateData 分页获取
func (c *SysDictService) GetPaginateData(params url.Values) ([]*models.SysDictionary, Pagination) {
	//搜索、查询字段赋值
	c.WhereField = append(c.WhereField, new(models.SysDictionary).WhereField()...)

	var configs []*models.SysDictionary
	o := orm.NewOrm().QueryTable(new(models.SysDictionary))
	_, err := c.PaginateAndScopeWhere(o, params, func(cond *orm.Condition) *orm.Condition {
		cond = condition.TernaryOperator(params.Has("dicValue"), cond.And("dic_value", params.Get("dicValue")), cond)
		cond = condition.TernaryOperator(params.Has("dicKey"), cond.And("dic_key", params.Get("dicKey")), cond)
		cond = condition.TernaryOperator(params.Has("dicCode"), cond.And("dic_code", params.Get("dicCode")), cond)
		return cond
	}).All(&configs)
	if err != nil {
		return nil, c.Pagination
	}
	return configs, c.Pagination
}

func (c *SysDictService) GetSimpleDictById(id int64) (*models.SysDictionary, error) {
	key := fmt.Sprintf(DictionaryCacheSimple, id)
	return global.GetCache[*models.SysDictionary](key, func() (*models.SysDictionary, error) {
		dict := models.SysDictionary{}
		sysDict := new(models.SysDictionary)
		err := orm.NewOrm().QueryTable(sysDict).Filter("id", id).One(&dict, sysDict.SimpleField()...)
		return &dict, err
	})
}
func (c *SysDictService) GetDictByCodeKey(code, key string) (*models.SysDictionary, error) {
	m := models.SysDictionary{}
	err := orm.NewOrm().QueryTable(new(models.SysDictionary)).Filter("dic_code", code).Filter("dic_key", key).One(&m)
	return &m, err
}

func (c *SysDictService) GetDictValueById(id int64) (string, error) {
	key := fmt.Sprintf(DictionaryCacheValue, id)
	return global.GetCache[string](key, func() (string, error) {
		dict := models.SysDictionary{}
		err := orm.NewOrm().QueryTable(new(models.SysDictionary)).Filter("id", id).One(&dict, "dic_value")
		return dict.DicValue, err
	})
}
